
/**
* Copyright: Copyright (c) 2013-2014
* Company:西安汇龙科技股份有限公司
*/
package com.lyf.core.util;


import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

/**
 * 
* RSA 加密解密
* @author lyf
* @version V1.0
* @date 2017年9月27日
 */
public class RSACoder {
	static Logger logger = Logger.getLogger(RSACoder.class);
	
    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    
	private static String private_key =  "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKkpnaPEQJoAVBuG9Oy5Dr+g6GM8"
            + "lyXoWkasSlu5N657umfuG9x7UYp9+sFGMFB1uyiNyuSB0ba6teOqudr3RtM6y+EPuLjblfJHY3Zt"
            + "cmJXMLYFN81ROI9AzbWC66H26n1/d9g8OvXLlqQfRqLpBOMecnza1/A63u3V47kHRWPBAgMBAAEC"
            + "gYBIo7QrlKRg/O8g+uzFkhnBM+lWY7hL8OCDJIyxonFEnaDH7DlOji3PmJVK1Ub95fA+U9TiFtTk"
            + "8HwWjUNNwY1JiF6NZzqAXGIGc1GAp9GyRYu/nLyOiRW56TKL8Ip/jGR6c+O5q9T25KNaRjiR9fjO"
            + "S0RUjbxRwjESuGTKlpZ5oQJBANQvaSQTORQaaQWP2VsHGEq/1kDOKIOdUl10/aMetjbVeGJ/4Bz0"
            + "R6P5vGsAcE1tHS8c4xvvI83uLdcVZHnpHz0CQQDMF+5l8ZZ+qztXL6eKEv7hUn+qP7uRAGu1qJ0Q"
            + "vKMPNIX5WCAm22MOSQ+3KMb4bVNQxdZrl/g7EIs4kxoHjl7VAkEAmfdJIN8+BMNhP6LxAmd0jhED"
            + "5AR0S4Sl1qDkxy+q4sEl2LuXoQr0zRyTR0WLN/OcQKqCdauiXHSfGLoyLXAmtQJAdCMGENKprcjo"
            + "ipNehg6LJVLZvNppdHjF0ehyAC0nqKZdumawXQwoUN+4ZqR4nLMxXtxFSJKAubOPVZE3lacpRQJA"
            + "GZaGYxdBSr0fkXusbhDTpZ4prn2KQyrjG4QiLuiT/WwPhvvIPcMKSkRcvTZk93HP5a4nqSizidvQ"
            + "1ZlGhChnDg==";

	
	private static String public_key =  "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpKZ2jxECaAFQbhvTsuQ6/oOhjPJcl6FpGrEpb"
		    + "uTeue7pn7hvce1GKffrBRjBQdbsojcrkgdG2urXjqrna90bTOsvhD7i425XyR2N2bXJiVzC2BTfN"
		    + "UTiPQM21guuh9up9f3fYPDr1y5akH0ai6QTjHnJ82tfwOt7t1eO5B0VjwQIDAQAB";

	
    public static byte[] decryptBASE64(String key) {
        return Base64.decodeBase64(key);
    }

    public static String encryptBASE64(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       加密数据
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        // 解密由base64编码的私钥
        byte[] keyBytes = decryptBASE64(privateKey);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取私钥匙对象
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data);
        return encryptBASE64(signature.sign());
    }

    /**
     * 校验数字签名
     *
     * @param data      加密数据
     * @param publicKey 公钥
     * @param sign      数字签名
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign)
            throws Exception {
        // 解密由base64编码的公钥
        byte[] keyBytes = decryptBASE64(publicKey);
        // 构造X509EncodedKeySpec对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取公钥匙对象
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(data);
        // 验证签名是否正常
        return signature.verify(decryptBASE64(sign));
    }

    public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception{
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 解密<br>
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(String data, String key)
            throws Exception {
        return decryptByPrivateKey(decryptBASE64(data),key);
    }
    
    public static String decryptByPrivateKey(String data)  {
        byte[] datas;
		try {
			datas = decryptByPrivateKey(decryptBASE64(data),private_key);

	        return new String(datas);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("decrypt error.data:" + data , e); //e.printStackTrace();
		}
    
		return null;
    }
    
    public static String encryptByPublicKey(String data)  {
        byte[] datas;
		try {
			
			datas = encryptByPublicKey(data, public_key);
			  
	        return encryptBASE64(datas) ;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("decrypt error.data:" + data , e); //e.printStackTrace();
		}
    
		return null;
    }

    /**
     * 解密<br>
     * 用公钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 加密<br>
     * 用公钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(String data, String key)
            throws Exception {
        // 对公钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data.getBytes());
    }

    /**
     * 加密<br>
     * 用私钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 取得私钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Key> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 取得公钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Key> keyMap)
            throws Exception {
        Key key = keyMap.get(PUBLIC_KEY);
        return encryptBASE64(key.getEncoded());
    }

    /**
     * 初始化密钥
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Key> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        Map<String, Key> keyMap = new HashMap<String,Key>(2);
        keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥
        keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥
        return keyMap;
    }
    
    public static void main(String[] args) throws Exception {
		/*String key = "QjhXzIRlSHb/HPPb+KSevM27q/dmBSqxED5+SEiKxfZzaUIzEBNGnWEXtH2bTmqmKZPulzamv/NjSaX8DDhyKR4YZ42Khmi1ZMvtJpkeMv/oxAq5K5NwIOOWxQQ9qogLoLRAHBUul0GKWap2JLApbvQ/93Wp9e65eAJh82aiIqg=" ;
				
		String private_key =  "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKkpnaPEQJoAVBuG9Oy5Dr+g6GM8"
                + "lyXoWkasSlu5N657umfuG9x7UYp9+sFGMFB1uyiNyuSB0ba6teOqudr3RtM6y+EPuLjblfJHY3Zt"
                + "cmJXMLYFN81ROI9AzbWC66H26n1/d9g8OvXLlqQfRqLpBOMecnza1/A63u3V47kHRWPBAgMBAAEC"
                + "gYBIo7QrlKRg/O8g+uzFkhnBM+lWY7hL8OCDJIyxonFEnaDH7DlOji3PmJVK1Ub95fA+U9TiFtTk"
                + "8HwWjUNNwY1JiF6NZzqAXGIGc1GAp9GyRYu/nLyOiRW56TKL8Ip/jGR6c+O5q9T25KNaRjiR9fjO"
                + "S0RUjbxRwjESuGTKlpZ5oQJBANQvaSQTORQaaQWP2VsHGEq/1kDOKIOdUl10/aMetjbVeGJ/4Bz0"
                + "R6P5vGsAcE1tHS8c4xvvI83uLdcVZHnpHz0CQQDMF+5l8ZZ+qztXL6eKEv7hUn+qP7uRAGu1qJ0Q"
                + "vKMPNIX5WCAm22MOSQ+3KMb4bVNQxdZrl/g7EIs4kxoHjl7VAkEAmfdJIN8+BMNhP6LxAmd0jhED"
                + "5AR0S4Sl1qDkxy+q4sEl2LuXoQr0zRyTR0WLN/OcQKqCdauiXHSfGLoyLXAmtQJAdCMGENKprcjo"
                + "ipNehg6LJVLZvNppdHjF0ehyAC0nqKZdumawXQwoUN+4ZqR4nLMxXtxFSJKAubOPVZE3lacpRQJA"
                + "GZaGYxdBSr0fkXusbhDTpZ4prn2KQyrjG4QiLuiT/WwPhvvIPcMKSkRcvTZk93HP5a4nqSizidvQ"
                + "1ZlGhChnDg==";
		
		
		String datas = decryptByPrivateKey(key);
		
		//System.out.println(new String(datas));
		
		String data = "BWqkEvpxX4/1qjmvgt2i/yM29sewb2ayTtFPW259sHkYNEbSKCytbxafChGswfwclnehyWHvL4qToECKSyZUaWy9ZoQwCnHVgGrJuY/uOFM48RB2VPhyu/wFVoANf3J9h1JeFl6CwWlibQpzcicwUB8eMOb8XJKXv/5sS8cef/M=" ;
		
		String data2 = URLEncoder.encode(data, "UTF-8");
		System.out.println(data2);
		*/
    	String data = "mrtest123" ;
    	
    	String s = encryptByPublicKey(data);
    	System.out.println(s);
    	
    	
    	s = "YZm+vRCPx/pS+cUsdtEGA8gzuGOBLykXOZyNXsJpenXuudoeUjkEEbM3b3YpSVoOWZKeM/IaNdjVz+SmkObioTBeYBukshWCMBYQCOSbkJjyM2Cfw5WxEtDOQ9Ft3oB4p0uLgk8tvPEQXJPg9QZ1EL2EqlLqyFAtIoEyQ2C50ZY=" ;
    	
    	String s2 = java.net.URLEncoder.encode(s, "UTF-8");
    	System.out.println(s2);
    	 String d2 = decryptByPrivateKey(s);
    	 
     System.out.println(d2);
    	
    	 byte[] bs = decryptBASE64("123");
    	 
    	for(byte b : bs){
    		System.out.println(b);
    	}
    	 
	}
}
